
import 'dart:async';

import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/util/timer_manager.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/borrow_entity.dart';
import '../entity/operate_reuqest_entity.dart';
import '../event/inventory_rfid_event.dart';
import '../main.dart';
import '../serial/three_to_one_manager.dart';
import '../widget/app_bar.dart';
import '../widget/circle_progress_widget.dart';


class Borrow extends StatefulWidget {
  const Borrow({Key? key}) : super(key: key);

  @override
  State<Borrow> createState() => _BorrowState();
}

class _BorrowState extends State<Borrow> {

  final RxList<BorrowEntity> _list = RxList();
  ThreeToOneManager manager = ThreeToOneManager();
  StreamSubscription? borrowSubscription;

  RxInt currentBorrowCount = 0.obs;


  @override
  initState() {
    super.initState();
    tts.speak('请将图书标签贴至扫描区');

    borrowSubscription = eventFactory.on<InventoryRfidEvent>().listen((event) {
        if(_list.map((element) => element.bookNo).contains(event.no)) {
          _setModeAndStart();
          return;
        }
        _borrow(event.rfid,event.no);
    });


    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.until((route) => route.isFirst);
      });
    });

    _setModeAndStart();
  }

  _setModeAndStart(){
    try{
      manager.setModeAndStart(Mode.inventory,isBorrow: true);
    }catch(e){
      toastWarn('三合一读写器配置错误');
      print(e);
    }
  }

  @override
  void dispose() {
    borrowSubscription?.cancel();
    borrowSubscription = null;
    super.dispose();
  }

  _borrow(rfid,book) async {
    if(book == null){
      toastWarn('条码号异常');
    }else{
      var data = await bookBorrow(currentTask.uid, book);
      if(data != null){
        tts.speak('借阅成功');
        currentBorrowCount.value = currentBorrowCount.value +1;
        _list.insert(0, data);
        _renew(rfid);
      }
    }
    _setModeAndStart();
  }

  _renew(String rfid) {
    if(rfid.length%2 == 1){
      rfid = "${rfid}0";
    }
    var i = rfid.length;
    var uid = '';
    while(i-2>=0){
      uid += rfid.substring(i-2,i);
      i = i-2;
    }

    var list  = [];
    list.add(OperateReuqestEntity()
      ..rfid = uid
      ..place = ''
      ..category = 'off'
      ..toJson()
    );
    operate(list);

  }


  _title(){
    return Container(
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: (){
              currentTask.clear();
              timer.cancel();
              manager.setMode(Mode.none);
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,),
          ),
          Text("借阅列表",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
          Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
        ],
      )
    );
  }


  _itemBuilder(index){
    var item = _list[index];
    return Container(
      padding: EdgeInsets.only(top: 16.h,bottom: 36.h,left: 26.w,right: 16.w),
      decoration: const BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.fill,
          image: AssetImage(
            "assets/images/borrow_item_bg.png",
          ),
        ),
      ),
      // alignment: Alignment.center,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Image.asset("assets/images/item_icon.png",width: 10.w,fit: BoxFit.fitWidth,),
              SizedBox(width: 290.w,child: Text(' ${item.bookTitle}',style: TextStyle(color: Colors.blueAccent,fontSize: 10.sp)),),
              Text('借阅成功',style: TextStyle(color:  const Color.fromRGBO(19, 136, 8, 1),fontSize: 10.sp))
            ],
          ),
          SizedBox(height: 5.h,),
          const Divider(height: 1.0,color: Colors.grey,),
          SizedBox(height: 10.h,),
          Text('图书编号：${item.bookNo}',style: TextStyle(color: Colors.grey,fontSize: 8.sp)),
          Text('归还时间：${item.readyReturnDate}',style: TextStyle(color: Colors.grey,fontSize: 8.sp))
        ],
      )
    );
  }

  _gif(){
    return Container(
      alignment: Alignment.bottomRight,
      margin: EdgeInsets.only(top: 300.h),
      width: double.infinity,
      padding: EdgeInsets.only(left: 50.w),
      child: Image.asset("assets/images/guide_gif.gif",),
    );
  }

  _person(){
    currentBorrowCount.value = currentTask.readerEntity!.currentBorrowCount!;
    return Container(
        margin: EdgeInsets.only(left: 8.w,right: 8.w),
        height: 100.h,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/person_info_bg.png",
            ),
          ),
        ),
        child: Stack(
          alignment: AlignmentDirectional.centerStart,
          children: [
            Positioned(left:50.w,child: Image.asset("assets/images/head.jpg",width: 60.w,fit: BoxFit.fitWidth,),),
            Positioned(left:130.w,top:33.h,child: Text("${currentTask.uName}",style: TextStyle(color: Colors.blue,fontSize: 12.sp,fontWeight: FontWeight.bold),),),
            Positioned(left:130.w,top:55.h,child: Text("读者证号:${currentTask.uid}",style: TextStyle(color: Colors.blue,fontSize: 10.sp,fontWeight: FontWeight.bold),),),
            Positioned(
                right: 30.w,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Obx(() => CircleProgress(size: 60.w,strokeWidth: 3.w,percent: currentBorrowCount.value/currentTask.readerEntity!.limitCount!,color: Colors.blue,)),
                    Container(
                      width: 50.w,
                      height: 50.w,
                      decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.all(Radius.circular(25.r)),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Obx(() => Text('${currentBorrowCount.value}/${currentTask.readerEntity!.limitCount}',style: TextStyle(color: Colors.white,fontSize: 10.sp,fontWeight: FontWeight.bold),)),
                          Text('借阅数量',style: TextStyle(color: Colors.white,fontSize: 6.sp),)
                        ],
                      ),
                    )
                  ],
                )
            ),
          ],
        )
    );
  }

  _books(){
    return  Obx(() => _list.isEmpty? _gif():
        Expanded(child: ListView.builder(
          itemBuilder: (context, index) {
            return _itemBuilder(index);
          },
          itemCount: _list.length,
        ))
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(),
            _title(),
            _person(),
            _books(),

          ],
        ),
      ),
    );
  }
}

